﻿
(function ($) {
    /*
    * iwss-lib JavaScript库
    * @namespace iwss
    * @name iwss
    */
    var iwss = window.iwss = {
        init: function () {
            iwss.url.loadPar();
            iwss.ctx.folder = '';
            iwss.evt.init();
        },
        ctx: {
            weburl: window.location.protocol + "//" + window.location.host + _spPageContextInfo.webServerRelativeUrl,
            siteurl: window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl,
            rootfolder: '',
            folder: '',
            user: '', //User.LoginName
            listid: '',
            sitem: '',
            init: function () {
                /* iwss.ajax.call("fileaction", { act: "context" }, function (res) {

                }, null, null, true);*/
            }
        },
        sys: {

            reload: function (url) {
                location.href = url;
            },
            editmode: function () {
                var publishingEdit = window.g_disableCheckoutInEditMode,
                form = document.forms[MSOWebPartPageFormName], input = form.MSOLayout_InDesignMode || form._wikiPageMode;
                return !!(publishingEdit || (input && input.value));
            }
        },
        url: {
            loadPar: function () {
                var args = new Object();
                var query = location.search.substring(1); // get query string 
                var pairs = query.split("&"); //www.cxybl.com break at ampersand 
                for (var i = 0; i < pairs.length; i++) {
                    var pos = pairs[i].indexOf('='); // look for "name=value" 
                    if (pos == -1) continue; // if not found, skip 
                    var argname = pairs[i].substring(0, pos); // extract the name 
                    var value = pairs[i].substring(pos + 1); // extract the value 
                    value = decodeURIComponent(value); // decode it, if needed 
                    args[argname] = value; // store as a property 
                }
                var ss = args.valueOf(0);
                iwss.urlPars = args;
                return args; // return the object
            },
            edit: function (name, value, reload) {
                var tempPar = iwss.urlPars;

                for (par in tempPar) {
                    if (par.toUpperCase() == name.toUpperCase()) {
                        tempPar[par] = value;
                    }
                }
                var tempurl = location.pathname + '?';
                for (par in tempPar) {
                    tempurl += par + '=' + tempPar[par] + '&';
                }

                if (typeof reload != 'undefined' && reload) {
                    iwss.sys.reload(tempurl);
                }

                return tempurl.substring(0, tempurl.length - 1);
            },
            get: function (name) { return iwss.urlPars[name] },
            remove: function (name, reload) {
                var tempPar = iwss.urlPars;
                var tempurl = location.pathname + '?';

                for (par in tempPar) {
                    if (par != name) {
                        tempurl += par + '=' + tempPar[par] + '&';
                    }
                }

                if (typeof reload != 'undefined' && reload) {
                    iwss.sys.reload(tempurl);
                }

                return tempurl.substring(0, tempurl.length - 1);
            },
            add: function (name, value, reload) {
                var hasPar = location.search != '';
                var tempurl = '';
                if (hasPar) {

                    if (iwss.urlPars[name] != null)
                        tempurl = thcnu.edit(name, value);
                    else
                        tempurl = location.href + "&" + name + '=' + value;

                } else {
                    tempurl = location.href + '?' + name + '=' + value;
                }

                if (typeof reload != 'undefined' && reload) {
                    iwss.sys.reload(tempurl);
                }

                return tempurl;
            },
            path: function () {
                return location.href.substring(0, location.href.lastIndexOf("/"));
            } (),
            host: function () {
                return location.protocol + "//" + location.hostname;
            } ()
        },
        ui: {
            dialog: function (url, title, callback, width, height, html) {
                var dialogOptions = {
                    title: title,
                    width: width,
                    height: height,
                    scrollbars: true,
                    status: true
                };

                if (typeof html != 'undefined') {
                    dialogOptions.html = $(html).clone().get(0);
                    dialogOptions.scrollbars = false;
                }
                else {
                    dialogOptions.url = url;
                }

                if (typeof callback != 'undefined')
                    dialogOptions.dialogReturnValueCallback = Function.createDelegate(null, callback);

                SP.UI.ModalDialog.showModalDialog(dialogOptions);
            },
            close: function (msg, reload, url) {
                ExecuteOrDelayUntilScriptLoaded((function () {
                    if (msg)
                        iwss.evt.notice(msg);
                    if (reload) {
                        if (url)
                            window.top.location.href = url;
                        else
                            iwss.sys.reload(location.href);
                    }
                    if (!msg) msg = '/';
                    SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, msg);
                }), "sp.js");
            },
            //遮罩层，一个Loading层，用于提示正在加载
            mask: function (obj, info) {
                if (typeof info == 'undefined') info = ''; // "正在处理中...";
                var maskhtml = '<div class="masklayer"></div>';
                var loadinghtml = '<div id="loading" class="border"><img src="' + decodeURIComponent(iwss.ctx.weburl) + '/_layouts/iwss.Document/images/loading.gif" alt=" " /> ' + info + '</div>';
                var self = $(obj);

                var w = self.get(0).scrollWidth;
                var h = self.get(0).scrollHeight;

                self.onscroll = function () { return false; }
                //self.css('overflow', 'hidden');

                var loadingWidth = 80; //  $(loadinghtml).scrollWidth();
                var loadingHeight = 20; // $(loadinghtml).scrollHeight();

                self.css("position", "relative").append($(maskhtml).css({ width: w + "px", height: h + "px", "line-height": h + "px" }));
                self.append($(loadinghtml).css({
                    left: ((self.outerWidth() / 2 + self.get(0).scrollLeft) - (loadingWidth / 2) + "px"),
                    top: ((self.outerHeight() / 2 + self.get(0).scrollTop) - (loadingHeight / 2) + "px")
                }));

                //$('#loading').focus();
                document.onkeydown = function (e) { return true; }
            },
            //取消遮罩层
            clear: function (obj) {
                var self = $(obj);
                self.onscroll = function () { return true; }
                self.find('div.masklayer,div#loading').remove();
                //self.css('overflow', 'auto');
            }
        },
        ajax: {
            call: function (ActionType, params, successCallback, errorCallback, async, noloading) {
                if (!noloading)
                    iwss.ui.mask('.center-wrap');
                var serviceUrl = iwss.ctx.weburl + "/_layouts/iwss.Document/ActionServices.ashx";
                if (!async) async = false;

                typeof (errorCallback) === 'undefined' ? errorCallback = function (a) { iwss.evt.notice(a) } : '';

                $.ajax({
                    url: serviceUrl,
                    async: async,
                    data: $.extend({}, {}, {
                        ActionType: ActionType
                    }, params),
                    dataType: "json",
                    success: function (result) {
                        if (result.Success) {
                            if (typeof (successCallback) !== 'undefined') {
                                successCallback(result);
                                iwss.ui.clear('.center-wrap');
                            }
                            else {
                                iwss.evt.notice("已经成功：" + result.Data.toString());
                            }
                        }
                        else {
                            errorCallback(result);
                        }
                    },
                    error: function (e) {
                        errorCallback("请求失败，请重试！");
                        iwss.ui.clear('.center-wrap');
                    }
                });
            }
        },
        action: {
            del: function (id) {

                var selected = $("#fileContent input:checked");
                var tempids = '';
                var ct = '';
                selected.each(function () {
                    tempids += $(this).attr("ItemID") + ",";
                    ct = $(this).attr("ct");
                });
                if (tempids == '') {
                    iwss.evt.notice("请选择要删除的项!"); return;
                }
                iwss.ajax.call("fileaction", { act: "delete", ids: tempids, ct: ct }, function (a) {
                    iwss.evt.notice("删除成功!");

                    selected.each(function () {
                        $(this).parents("li").remove();
                    });

                });
            },
            checkall: function (check) {
                $("#fileContent input[type=checkbox]").attr('checked', check);
            },
            upload: function () {

                var url = String.format('{0}/_layouts/Upload.aspx?List={1}&RootFolder={2}', iwss.ctx.weburl, iwss.ctx.listid, encodeURIComponent(iwss.ctx.folder));

                iwss.ui.dialog(url, "上传文件", function (a, b) {
                    // if (SP.UI.DialogResult.OK == a) {
                    //    iwss.evt.notice('共享成功');
                    iwss.action.get();
                    // }
                });
            },
            share: function () {
                var docs = '';
                var selected = $("#fileContent input:checked");
                if (selected.length == 0) {
                    iwss.evt.notice("请选择需要共享的文件"); return;
                }

                //新增可以共享别人共享给自己的文件
                selected.each(function () {
                    var self = $(this);
                    var field = self.attr("ct") == "share" ? "FileID" : "ItemID";
                    docs += self.attr(field) + ",";
                });

                var url = String.format('{0}/_layouts/iwss.Document/action/Share.aspx?docs={1}', iwss.ctx.weburl, encodeURIComponent(docs));

                iwss.ui.dialog(url, "共享文件", function (a, b) {
                    //go to sharer page
                    if (SP.UI.DialogResult.OK == a) {
                        iwss.evt.notice(b);
                        iwss.action.history();
                    }
                });
            },
            receive: function () {
                if (window.ReceivedData) return;

                iwss.ajax.call("receive", { act: "receive" }, function (res) {
                    if (res.Data.length > 0) {
                        window.ReceivedData = res.Data;
                        iwss.evt.show();
                    } else {
                        $("#cnu_NewShare").removeClass("left-newfile");
                    }
                }, null, false, true);
            },
            sharetome: function () {
                iwss.ajax.call("receive", { act: "Sharetome" }, function (res) {
                    $("#fileContent").html($("#ShareItemTmpl").tmpl(res.Data)).trigger("NewLoad"); //获取文件
                });
            },
            history: function () {//最近使用文档
                iwss.ajax.call("other", { act: "history" }, function (res) {
                    $("#fileContent").html($("#ShareItemTmpl").tmpl(res.Data)).trigger("NewLoad"); //获取文件
                });
            },
            linkman: function () {//最近联系人
                iwss.ajax.call("other", { act: "linkman" }, function (res) {

                });
            },
            get: function (folder, subfolder) {
                if (!folder) folder = iwss.ctx.folder;
                else iwss.ctx.folder = folder;

                iwss.ajax.call("fileaction", { act: "get", folder: folder, subfolder: subfolder }, function (res) {

                    $("#fileContent").html($("#FileItemTmpl").tmpl(res.Data.Files)).trigger("NewLoad");;
                    $("#folderContent").html($("#FolderItemTmpl").tmpl(res.Data.Folders)); //获取文件夹

                    //其它附加信息
                    iwss.ctx.folder = res.Addition.FolderUrl;
                    iwss.ctx.listid = res.Addition.ListID;

                });
            },
            load: function () {
                if (!window.ReceivedData) return;

                $("#fileContent").html($("#FileItemTmpl").tmpl(window.ReceivedData)).trigger("NewLoad"); //获取文件
                var recedids = '';
                $(window.ReceivedData).each(function () {
                    recedids += this.ItemID + ",";
                });
                recedids = encodeURIComponent(recedids);

                //标记为已读
                iwss.ajax.call("receive", { act: "setflag", ids: recedids }, function () {
                    window.ReceivedData = null;
                    clearInterval(window.audio);
                    clearInterval(window.newmsg);
                    document.title = window._title;
                }, null, null, true);
            },
            up: function () {
                var turl = iwss.ctx.folder.substring(0, iwss.ctx.folder.lastIndexOf("/"));
                iwss.action.get(turl);
            },
            index: function () {
                location.href = iwss.ctx.weburl;
            }
        },
        evt: {
            bind: function () {
                $(function () {
                    $("#fileContent").on("click", '.file-list-item', function (e) {
                        if (e.target != this) {
                            return;
                        }
                        var cinput = $(this).find("input[type=checkbox]").get(0);
                        cinput.checked = !cinput.checked;
                    });

                    $(".left-item").click(function () {
                        $(".left-item-selected").removeClass("left-item-selected");
                        $(this).addClass("left-item-selected");
                    });

                    $(".top-nav-item").click(function () {
                        $(".top-nav-item-selected").removeClass("top-nav-item-selected");
                        $(this).addClass("top-nav-item-selected");
                    });

                    $("#jplayer").jPlayer({
                        swfPath: iwss.ctx.weburl + "/_layouts/iwss.Document/scripts/media/Jplayer.swf",
                        ready: function () {
                            $(this).jPlayer("setMedia", {
                                mp3: iwss.ctx.weburl + "/_layouts/iwss.Document/scripts/media/message.mp3"
                            });
                        },
                        supplied: "mp3"
                    });

                    $("ul#fileContent").bind("NewLoad", function (event, type, length) {
                        $("div.page-container").remove();
                        //加载翻页 
                        //alert($(this).find("li").length);

                        $(this).easyPaginate({
                            step: 8,
                            ContainerCss: "page-container"
                        });
                    })


                    iwss.action.get();
                });
            },
            init: function () {
                iwss.evt.bind();

                setInterval(function () {
                    iwss.action.receive();
                }, 10000);
            },
            show: function () {

                //play music or animation
                $("#cnu_NewShare").addClass("left-newfile");

                window.step = 0, window._title = document.title;
                window.newmsg = setInterval(function () {
                    step++;
                    if (step == 3) { step = 1 };
                    if (step == 1) { document.title = '【　　　】您收到了' + window.ReceivedData.length + "个新文件" + _title };
                    if (step == 2) { document.title = '【新消息】您收到了' + window.ReceivedData.length + "个新文件" + _title };
                }, 500);
                window.audio = setInterval(function () {
                    $("#jplayer").jPlayer('play');
                }, 5000);
            },
            notice: function (msg) {
                ExecuteOrDelayUntilScriptLoaded((function () {
                    SP.UI.Notify.addNotification(msg, false, "", null);
                }), "sp.js");
            }
        }
    }
    iwss.init();
})($); 
